package com.crishne.anwo.utill;

import java.security.MessageDigest;


/**
 * Title: ACL安全工具类
 * Project: 
 * @author ZLx
 * Description: 
 * Copyright: 
 * Company: 
 */
public class AclSecurityUtil {
	// ====================================================================================================
	// 可选算法（推荐SHA1）
	// ====================================================================================================
	public static final String ALGORITHM_MD5 = "MD5";
	public static final String ALGORITHM_SHA1 = "SHA1";
	// ////////////////////////////////////////////////////////////////////////////////////////////////////
	private static char[] hexChars = "0123456789abcdef".toCharArray();
	
	private String _algorithm = null;
	private AclSecurityUtil(String algorithm) {
		this._algorithm = algorithm;
	}
	
	/**
	 * 获取类实例工厂方法
	 * @param algorithm 算法（MD5或SHA1，推荐SHA1）
	 * @return
	 */
	public static AclSecurityUtil getInstance(String algorithm) {
		return new AclSecurityUtil(algorithm);
	}
	
	/**
	 * 加密密码
	 * @param password 明码密码
	 * @return 加密后的密码（40位）
	 * @throws Exception
	 */
	public String encodePassword(String password) throws Exception {
		if ( null == password ) {
			return null;
		}
		MessageDigest digest = null;
		digest = MessageDigest.getInstance(this._algorithm);
		byte[] by = digest.digest(password.getBytes());
		return hexString(by);
	}

	/**
	 * 检查密码
	 * @param password 明码密码（供检查）
	 * @param digest 密文密码（来自数据库）
	 * @return 是否匹配
	 * @throws Exception
	 */
	public boolean checkPassword(String password, String digest) throws Exception {
		String digestCheck = this.encodePassword(password);
		if ( null == digestCheck || "".equals(digestCheck) ) {
			return false;
		} else {
			if ( digestCheck.equals(digest) ) {
				return true;
			} else {
				return false;
			}
		}
	}
	
	private String hexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		for (byte b : bytes) {
			sb.append(hexChars[b >>> 4 & 15]).append(hexChars[b & 15]);
		}
		return sb.toString();
	}

	public static void main(String[] args) throws Exception {
		AclSecurityUtil asu = AclSecurityUtil.getInstance(ALGORITHM_SHA1);
		String password = "1";
		String digest = asu.encodePassword(password);
		System.out.println("digest=" + digest); // TODO System.out.println();
		boolean check = asu.checkPassword(password, digest);
		System.out.println("check=" + check); // TODO System.out.println();
	}
	
	
}
